// pages/profile/profile.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatar: 'https://images.unsplash.com/photo-1608889825103-eb5ed706fc64?q=80&w=400',
      nickname: '微醺调酒师',
      level: 1,
      levelTitle: '微醺学徒'
    },
    stats: {
      favorites: 0,  // 收藏特调数量
      recipes: 0,    // 创建特调数量
    },
    totalPoints: 0,  // 微醺积分
    levelProgress: 0,  // 当前等级进度
    nextLevelNeeds: 0, // 距离下一等级需要的收藏数
    nextLevelNeedsRecipe: 0, // 距离下一等级需要的特调数
    tabBarActive: 3,
    showLevelModal: false,
    perfumeHistory: [],
    isDarkMode: false,
    // 等级体系配置
    levelSystem: [
      { level: 1, title: '微醺学徒', favRange: [0, 5], recipeRange: [0, 2], benefit: '新手调酒工具包（初识酒香）' },
      { level: 2, title: '巷口小酒仙', favRange: [6, 15], recipeRange: [3, 5], benefit: '解锁风味笔记功能（探索街头酒馆）' },
      { level: 3, title: '琥珀收藏家', favRange: [16, 30], recipeRange: [6, 10], benefit: '私人酒柜空间+1（开始窖藏时光）' },
      { level: 4, title: '霓虹调酒师', favRange: [31, 50], recipeRange: [11, 20], benefit: '专属鸡尾酒命名权（城市夜酒馆主理人）' },
      { level: 5, title: '风味炼金士', favRange: [51, 80], recipeRange: [21, 35], benefit: '配方实验室（创造分子级味觉魔法）' },
      { level: 6, title: '百年酒窖主', favRange: [81, 120], recipeRange: [36, 50], benefit: '虚拟地下酒窖（传承百年酿酒世家）' },
      { level: 7, title: '微醺哲学家', favRange: [121, 180], recipeRange: [51, 70], benefit: '酒神对话特权（参透杯中人生哲学）' },
      { level: 8, title: '星河蒸馏者', favRange: [181, 250], recipeRange: [71, 100], benefit: '太空陈酿舱（在星际间萃取极致风味）' },
      { level: 9, title: '酒神代行者', favRange: [251, 350], recipeRange: [101, 150], benefit: '创立虚拟酒厂（凡人肉身承载神性）' },
      { level: 10, title: '杯中之神', favRange: [351, 120000], recipeRange: [151, 120000], benefit: '永恒微醺圣殿（超越系统的终极存在）' }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const isDark = wx.getStorageSync('isDarkMode');
    this.setData({
      isDarkMode: typeof isDark === 'boolean' ? isDark : (getApp().globalData.isDarkMode || false)
    });
    // 每次显示页面时更新统计数据
    this.updateUserStats();
    
    // 设置TabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: this.data.tabBarActive
      });
    }
    // === 新增：获取后端香水历史推荐 ===
    wx.request({
      url: 'http://localhost:3000/api/history', // 替换为你的服务器地址
      method: 'GET',
      data: {
        category: 'perfume',
        userId: '' // 如有用户ID可填写
      },
      success: (res) => {
        this.setData({ perfumeHistory: res.data.list });
      }
    });
    // === 新增结束 ===
  },
  
  /**
   * 更新用户统计数据
   */
  updateUserStats: function() {
    try {
      // 获取收藏数量
      const collectionList = wx.getStorageSync('cocktail_collection') || [];
      // 获取历史配方数量
      const historyList = wx.getStorageSync('cocktail_history') || [];
      
      const favCount = collectionList.length;
      const recipeCount = historyList.length;
      
      // 计算当前等级和称号
      const levelInfo = this.calculateUserLevel(favCount, recipeCount);
      
      // 计算微醺积分（收藏×2 + 特调×3）
      const totalPoints = favCount * 2 + recipeCount * 3;
      
      // 计算距离下一等级的需求
      const nextLevelNeeds = this.calculateNextLevelNeeds(favCount, recipeCount);
      
      this.setData({
        'stats.favorites': favCount,
        'stats.recipes': recipeCount,
        'userInfo.level': levelInfo.level,
        'userInfo.levelTitle': levelInfo.title,
        totalPoints: totalPoints,
        levelProgress: levelInfo.progress,
        nextLevelNeeds: nextLevelNeeds.favorites,
        nextLevelNeedsRecipe: nextLevelNeeds.recipes
      });
    } catch (e) {
      console.error('获取用户统计数据失败:', e);
    }
  },
  
  /**
   * 计算用户等级和称号
   */
  calculateUserLevel: function(favCount, recipeCount) {
    const levelSystem = this.data.levelSystem;
    let currentLevel = 1;
    let currentTitle = levelSystem[0].title;
    let progress = 0;
    
    // 遍历等级体系，找出当前等级
    for (let i = levelSystem.length - 1; i >= 0; i--) {
      const level = levelSystem[i];
      if (favCount >= level.favRange[0] || recipeCount >= level.recipeRange[0]) {
        currentLevel = level.level;
        currentTitle = level.title;
        
        // 计算当前等级的进度
        if (i < levelSystem.length - 1) {
          const nextLevel = levelSystem[i + 1];
          const favProgress = ((favCount - level.favRange[0]) / (nextLevel.favRange[0] - level.favRange[0])) * 100;
          const recipeProgress = ((recipeCount - level.recipeRange[0]) / (nextLevel.recipeRange[0] - level.recipeRange[0])) * 100;
          progress = Math.min(Math.max(favProgress, recipeProgress), 100);
        } else {
          progress = 100; // 最高等级
        }
        break;
      }
    }
    
    return {
      level: currentLevel,
      title: currentTitle,
      progress: progress
    };
  },
  
  /**
   * 计算距离下一等级需要的数量
   */
  calculateNextLevelNeeds: function(favCount, recipeCount) {
    const levelSystem = this.data.levelSystem;
    const currentLevel = this.calculateUserLevel(favCount, recipeCount).level;
    
    if (currentLevel < levelSystem.length) {
      const nextLevel = levelSystem[currentLevel];
      return {
        favorites: Math.max(0, nextLevel.favRange[0] - favCount),
        recipes: Math.max(0, nextLevel.recipeRange[0] - recipeCount)
      };
    }
    
    return {
      favorites: 0,
      recipes: 0
    };
  },

  /**
   * 导航到我的收藏页面
   */
  navigateToFavorites: function() {
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    });
  },

  /**
   * 导航到我的特调页面
   */
  navigateToMyCocktails: function() {
    wx.navigateTo({
      url: '/pages/my_cocktails/my_cocktails'
    });
  },

  /**
   * 导航到浏览历史页面
   */
  navigateToHistory: function() {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  /**
   * 显示等级系统弹窗
   */
  navigateToLevels: function() {
    this.setData({
      showLevelModal: true
    });
  },

  /**
   * 关闭等级系统弹窗
   */
  closeLevelModal: function() {
    this.setData({
      showLevelModal: false
    });
  },

  /**
   * 防止穿透滚动
   */
  preventTouchMove: function() {
    return false;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '今日微醺 - 专属你的鸡尾酒特调',
      path: '/pages/index/index'
    };
  },

  navigateToAccount() {
    wx.navigateTo({
      url: '/pages/account/account'
    });
  },
  toggleDarkMode(e) {
    this.setData({ isDarkMode: e.detail.value });
    wx.showToast({
      title: e.detail.value ? '已开启夜间模式' : '已关闭夜间模式',
      icon: 'none'
    });
    // 实际项目可用全局状态管理
  },
  navigateToPrivacy() {
    wx.navigateTo({
      url: '/pages/privacy/privacy'
    });
  },
  navigateToFeedback() {
    wx.navigateTo({
      url: '/pages/feedback/feedback'
    });
  },
  navigateToAbout() {
    wx.navigateTo({
      url: '/pages/about/about'
    });
  },
  logout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorageSync();
          wx.reLaunch({ url: '/pages/index/index' });
        }
      }
    });
  },
  navigateToSettings() {
    wx.navigateTo({ url: '/pages/settings/settings' });
  },
  updateTheme(isDark) {
    this.setData({ isDarkMode: isDark });
  },
  navigateToHelp() {
    wx.navigateTo({ url: '/pages/feedback/feedback' });
  },
  navigateToAbout() {
    wx.navigateTo({ url: '/pages/about/about' });
  },
  navigateToOfflineBars: function() {
    wx.navigateTo({
      url: '/pages/bar/bar'
    });
  },
  navigateToTools: function() {
    wx.navigateTo({
      url: '/pages/tools/tools'
    });
  },
  navigateToPerfumeShop: function() {
    wx.navigateTo({
      url: '/pages/perfume_shop/perfume_shop'
    });
  },
  navigateToAmbilight: function() {
    wx.navigateTo({
      url: '/pages/ambilight/ambilight'
    });
  },
}) 